package com.sbm.swagger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerBuilder {
	private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerBuilder.class);

	@Autowired
	private SwaggerConfig config;

	@Bean
	public Docket buildRestApi() {
		LOGGER.info("————Swagger初始化————");
		LOGGER.info("扫描路径：" + this.config.getBasePackage());
		LOGGER.info("文档标题：" + this.config.getTitle());
		LOGGER.info("文档描述：" + this.config.getDescription());
		LOGGER.info("服务地址：" + this.config.getTermsOfServiceUrl());
		LOGGER.info("服务条款：" + this.config.getLicense());
		LOGGER.info("条款地址：" + this.config.getLicense());
		LOGGER.info("文档版本：" + this.config.getVersion());
		LOGGER.info("开发团队：" + this.config.getContact());
		Docket docket = new Docket(DocumentationType.SWAGGER_2);
		docket.enable(true);
		docket.apiInfo(buildApiInfo());
		docket.genericModelSubstitutes(ResponseEntity.class);
		docket.useDefaultResponseMessages(true);
		docket.forCodeGeneration(false);
		if (this.config.getGroupName() != null && this.config.getGroupName() != "")
			docket.groupName(this.config.getGroupName());
		ApiSelectorBuilder builder = docket.select();
		if (this.config.getBasePackage() != null && this.config.getBasePackage() != "")
			builder.apis(RequestHandlerSelectors.basePackage(this.config.getBasePackage()));
		else
			builder.apis(RequestHandlerSelectors.any());
		builder.paths(PathSelectors.any());
		return builder.build();
	}

	@SuppressWarnings("deprecation")
	@Bean
	public ApiInfo buildApiInfo() {
		ApiInfoBuilder builder = new ApiInfoBuilder();
		builder.title(this.config.getTitle());
		builder.description(this.config.getDescription());
		builder.license(this.config.getLicense());
		builder.licenseUrl(this.config.getLicenseUrl());
		builder.version(this.config.getVersion());
		builder.termsOfServiceUrl(this.config.getTermsOfServiceUrl());
		builder.contact(this.config.getContact());
		return builder.build();
	}
}
